<template>
  <div>
    <p>{{ title }}</p>
    <label v-for="(option, index) in options" :key="index">
      <input
        type="radio"
        :value="option.value"
        :id="`option-${index}`"
        v-model="selectedOption"
      />
      <span :for="`option-${index}`">{{ option.label }}</span>
    </label>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, watch } from "vue";

// 定义组件的props
const props = defineProps({
  modelValue: {
    type: [String, Number],
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
  title: {
    type: String,
    required: true,
  },
  index: {
    type: [String, Number],
    required: true,
  },
});

// 定义组件的emits
const emit = defineEmits(["change"]);

const selectedOption = ref(props.modelValue);

watch(
  () => props.modelValue,
  (newValue) => {
    selectedOption.value = newValue;
  }
);

watch(selectedOption, (value) => {
  let obj = {
    value: value,
    index: props.index,
  };
  emit("change", obj);
});

onMounted(() => {
  selectedOption.value = props.modelValue;
});
</script>